import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const currentUser = ref({
    id: null,
    username: '',
    nickname: '',
    email: '',
    phone: '',
    name: '',
    role: '',
    roles: [],
    avatar: ''
  })

  const isLoggedIn = ref(false)

  // 初始化：从localStorage恢复登录状态
  const initializeAuth = () => {
    const token = localStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo')

    if (token && userInfo) {
      try {
        // 先检查token是否有效
        import('../utils/tokenUtils').then(({ isTokenExpired }) => {
          if (isTokenExpired(token)) {
            console.log('Token已过期，清除登录状态')
            logout()
            return
          }

          const parsedUserInfo = JSON.parse(userInfo)
          setCurrentUser(parsedUserInfo)
          isLoggedIn.value = true // 确保设置登录状态
          console.log('从localStorage恢复登录状态成功')
        }).catch(error => {
          console.error('检查token失败:', error)
          logout()
        })
      } catch (error) {
        console.error('解析用户信息失败:', error)
        // 清除无效数据
        logout()
      }
    } else {
      isLoggedIn.value = false
    }
  }

  // 计算属性
  const isAdmin = computed(() => currentUser.value.roles && currentUser.value.roles.includes('管理员'))
  const isUser = computed(() => currentUser.value.roles && currentUser.value.roles.includes('用户'))

  // 方法
  const setCurrentUser = (userInfo) => {
    currentUser.value.id = userInfo.id
    currentUser.value.username = userInfo.username || userInfo.name
    currentUser.value.nickname = userInfo.nickname || ''
    currentUser.value.email = userInfo.email || ''
    currentUser.value.phone = userInfo.phone || ''
    currentUser.value.name = userInfo.name || userInfo.nickname
    currentUser.value.role = userInfo.role
    currentUser.value.roles = userInfo.roles || []
    currentUser.value.avatar = userInfo.avatar || ''
    isLoggedIn.value = true

    // 保存用户信息到localStorage
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  }

  const logout = () => {
    currentUser.value = {
      id: null,
      username: '',
      nickname: '',
      email: '',
      phone: '',
      name: '',
      role: '',
      roles: [],
      avatar: ''
    }
    isLoggedIn.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('userInfo')

    // 停止token自动刷新
    import('../utils/tokenUtils').then(({ stopTokenRefresh }) => {
      stopTokenRefresh()
    }).catch(() => {
      // 忽略导入错误
    })

    // 断开WebSocket连接
    import('../utils/websocket').then(({ default: webSocketManager }) => {
      webSocketManager.disconnect()
    }).catch(() => {
      // 忽略导入错误
    })
  }

  // 页面加载时初始化（延迟执行，避免与路由守卫冲突）
  setTimeout(() => {
    initializeAuth()
  }, 100)

  return {
    currentUser,
    isLoggedIn,
    isAdmin,
    isUser,
    setCurrentUser,
    logout,
    initializeAuth
  }
}) 